<script setup lang="ts">
import type { ButtonOnGetphonenumberEvent } from '@uni-helper/uni-app-types'
import { loginAPI } from '@/apis/login'
import { useUserInfoStore } from '@/store/userInfo'
import { getPhoneNumberAPI } from '@/apis/getPhoneNumber'

// 如果从班级详情等页面跳进来登录页面，则这个值不为空，则登录或完善信息后返回进来时的页面
const abnormal = ref('')

const router = useRouter()
const userInfoStore = useUserInfoStore()

const isAgree = ref(false)
const isShowDialog = ref(false)

onLoad((options) => {
  if (options && options.abnormal)
    abnormal.value = options.abnormal

  // 如果有 token，说明登录过了，检查手机号和必填信息有没有
  if (userInfoStore.userInfo?.token)
    completion(userInfoStore.userInfo)
  // 否则什么都不做，正常登录
})

function completion(userInfo: UserInfo) {
  // 如果没有手机号，提示绑定手机号
  if (!userInfo.mobile) {
    isShowDialog.value = true
    return
  }

  // 如果有手机号，但没完善信息，去完善信息
  if (!(userInfo.username
    && userInfo.company
    && userInfo.company_type
    && userInfo.duties)) {
    router.push({
      name: 'profileCompletion',
      params: {
        abnormal: abnormal.value,
      },
    })
  }

  if (abnormal.value) {
    // 从班级详情等别的页面进来的，登录完之后再返回去
    router.back()
  }
  else {
    // 进入首页
    router.replaceAll('home')
  }
}

const handleLogin = useThrottleFn(async () => {
  // 加载中状态
  uni.showLoading({ title: '加载中...' })

  // // 如果 baseUrl 还没加载到
  // if (!uni.getStorageSync('domain')) {
  //   try {
  //     const res = await fetchDomainAPI()
  //     if ((res.data as any).code === 1) { uni.setStorageSync('domain', (res.data as any).data) }
  //     else {
  //       uni.showToast({ title: (res.data as any).msg, icon: 'none' })
  //       uni.hideLoading()
  //     }
  //   }
  //   catch (err) {
  //     uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  //     uni.hideLoading()
  //   }
  // }

  // 如果没勾选同意
  if (!isAgree.value) {
    uni.hideLoading()
    uni.showToast({ title: '请先勾选用户协议和隐私政策', icon: 'none' })
    return
  }

  try {
    // 获取用户信息
    const profileRes = await uni.getUserProfile({
      desc: '展示用户信息',
    })
    // 获取 code
    const loginRes = await uni.login()

    // 使用 code 和加密数据换取 userInfo
    const res = await loginAPI({
      login_type: 'wechat',
      code: loginRes.code,
      iv: profileRes.iv,
      encryptedData: profileRes.encryptedData,
    })
    uni.hideLoading()

    const userInfo = res.data?.data.userinfo

    if (userInfo) {
      userInfoStore.setUserInfo(userInfo)
      completion(userInfo)
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err) })
    uni.hideLoading()
  }
}, 500)

async function handleGetPhoneNumber(e: ButtonOnGetphonenumberEvent) {
  try {
    const res = await getPhoneNumberAPI({
      code: e.detail.code!,
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1) {
      const phoneNumber = res.data?.data
      const userInfoWithPhoneNumber: UserInfo = { ...userInfoStore.userInfo!, mobile: phoneNumber }
      userInfoStore.setUserInfo(userInfoWithPhoneNumber)
      // 有手机号了，去完善信息
      router.push({
        name: 'profileCompletion',
        params: {
          abnormal: abnormal.value,
        },
      })
    }
    else {
      uni.showToast({ title: '绑定手机号失败', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}

function handleViewProtocol(type: string) {
  router.push({
    name: 'protocol',
    params: { type },
  })
}
</script>

<template>
  <view class="min-h-screen bg-white">
    <view class="min-h-screen flex flex-col items-center justify-between pb-48rpx">
      <view class="flex flex-col items-center">
        <Spacer height="194" />
        <image class="h-200rpx w-200rpx" src="@/static/images/logo.png" />
        <Spacer height="36" />
        <view class="text-48rpx text-#333333 font-semibold leading-68rpx">
          欢迎使用晋财干教
        </view>
        <view class="text-32rpx text-black leading-48rpx opacity-50">
          一月一培训数字化服务
        </view>
      </view>

      <view class="flex flex-col items-center">
        <button
          class="h-100rpx w-650rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white font-medium leading-30rpx"
          hover-class="bg-#3266D9"
          @tap="handleLogin"
        >
          手机号快捷登录
        </button>
        <Spacer height="12" />
        <view class="flex items-center p-20rpx" @tap="isAgree = !isAgree">
          <Checkbox :checked="isAgree" />
          <Spacer width="16" />
          <view class="text-24rpx text-#4D4D4D leading-32rpx">
            我已阅读并同意
            <text class="text-#0037AE" @tap.stop="handleViewProtocol('用户协议')">
              《用户协议》
            </text>
            和
            <text class="text-#0037AE" @tap.stop="handleViewProtocol('隐私政策')">
              《隐私政策》
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <view class="relative w-690rpx flex flex-col items-center rounded-14rpx bg-white" @tap.stop="">
            <image class="absolute right-36rpx top-36rpx h-27rpx w-27rpx" src="@/static/images/xmark.png" @tap="isShowDialog = false" />
            <Spacer height="45" />
            <view class="text-32rpx text-#333333 font-semibold leading-36rpx">
              授权手机号
            </view>
            <Spacer height="35" />
            <view class="text-26rpx text-#919191 leading-44rpx">
              初次使用请授权手机号
            </view>
            <Spacer height="68" />
            <view class="flex items-center">
              <button
                open-type="getPhoneNumber"
                class="h-80rpx w-604rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white leading-42rpx"
                hover-class="bg-#3266D9"
                @getphonenumber="handleGetPhoneNumber"
              >
                授权手机号
              </button>
            </view>
            <Spacer height="30" />
          </view>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'login'
style:
  navigationBarTitleText: '登录'
  disableScroll: true
layout: 'custom'
</route>
